package edu.cug.water.crawler.config;

import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ReqConfig {

    @Bean
    public RestTemplate simpleRestTemplate() {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        //OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory();

        requestFactory.setConnectionRequestTimeout(60000);
        requestFactory.setReadTimeout(60000);
        requestFactory.setConnectTimeout(60000);
        return new RestTemplate(requestFactory);
    }

    @Bean
    public RestTemplate httpsRestTemplate() {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        return new RestTemplate(requestFactory);
    }

    @Bean
    public RestTemplate restTemplateWithCookies(HttpComponentsClientHttpRequestFactory requestFactory) {
        requestFactory.setConnectionRequestTimeout(60000);
        requestFactory.setReadTimeout(60000);
        requestFactory.setConnectTimeout(60000);
        return new RestTemplate(requestFactory);
    }

    @Bean
    public HttpComponentsClientHttpRequestFactory requestFactory() {

        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.DEFAULT)
                .setExpectContinueEnabled(true)
                .build();

        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCookieStore(new BasicCookieStore())
                .setDefaultRequestConfig(defaultRequestConfig).build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        return requestFactory;
    }
}
